package com.dayuanit.filter;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dayuanit.content.Content;

public class LoginFilter implements Filter {

	private String whiteURL;

	@Override
	public void destroy() {
		System.out.println("LoginFilter is destroying...");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession hs = req.getSession();
		if (null != whiteURL) {
			String[] whiteURLs = whiteURL.split(";");
			for (int i = 0; i < whiteURLs.length; i++) {
				if (null == whiteURLs[i] || "".equals(whiteURLs[i])) {
					continue;
				}
				if (req.getRequestURI().indexOf(whiteURLs[i]) != -1) {
					chain.doFilter(request, response);
					return;
				}
			}
		}
		if (null != hs.getAttribute(Content.LOGIN_FLAG)) {
			chain.doFilter(request, response);
		} else {
			resp.sendRedirect(req.getServletContext().getContextPath() + "/user/toLogin.do");
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		System.out.println("LoginFilter is init...");
		String file = config.getInitParameter("whiteURL");
		String key = config.getInitParameter("whiteURLKey");
		Properties properties = new Properties();
		try {
			properties.load(this.getClass().getClassLoader().getResourceAsStream(file));
		} catch (IOException e) {
			e.printStackTrace();
		}
		whiteURL = (String) properties.get(key);
	}
}
